﻿using System;
using System.ComponentModel.Design;
using System.Linq;
using System.Reflection;
using System.Windows.Forms;

namespace Landpy.CruiseControlNet.Infrastructure.Control
{
    public class MultipleTypeCollectionEditor : CollectionEditor
    {
        private Type BaseType { get; set; }
        public static PropertyValueChanged ValueChangedEvent { set; private get; }

        public delegate void PropertyValueChanged(object sender, MultipleTypeCollectionEditorEventArgs eventArgs);

        public MultipleTypeCollectionEditor(Type type)
            : base(type)
        {
            this.BaseType = type.GetProperty("Item").PropertyType;
        }

        protected override Type[] CreateNewItemTypes()
        {
            var types = (from Type type in Assembly.GetAssembly(this.BaseType).GetTypes()
                         where type.IsSubclassOf(this.BaseType)
                         select type).ToArray();
            if (types.Length == 0)
            {
                return base.CreateNewItemTypes();
            }
            return types;
        }

        protected override CollectionForm CreateCollectionForm()
        {
            CollectionForm collectionForm = base.CreateCollectionForm();
            collectionForm.FormClosing += collectionForm_FormClosing;
            return collectionForm;
        }

        void collectionForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            var collectionForm = sender as CollectionForm;
            if (collectionForm != null && collectionForm.DialogResult == DialogResult.OK)
            {
                var propertyValueChangedEventArgs = new MultipleTypeCollectionEditorEventArgs(collectionForm.EditValue);
                ValueChangedEvent.Invoke(collectionForm, propertyValueChangedEventArgs);
            }
        }

    }
}
